package com.diaohw.platform.framework.db.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.diaohw.platform.common.obj.thread.LoginThread;
import com.diaohw.platform.framework.db.obj.BaseLogModel;
import com.diaohw.platform.framework.db.obj.BaseModel;
import com.diaohw.platform.framework.db.properties.MetaObjectHandlerProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@Component
public class GlobalMetaObjectHandler implements MetaObjectHandler {
    Optional<TenantLineHandler> optional;
    @Resource
    private MetaObjectHandlerProperties properties;

    @PostConstruct
    public void init() {
        try {
            optional = Optional.of(SpringUtil.getBean(TenantLineHandler.class));
        } catch (Exception ignore) {
            optional = Optional.empty();
        }

    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtil.isNull(metaObject)) {
            return;
        }
        fillTenantId(metaObject);

        if (metaObject.getOriginalObject() instanceof BaseModel<?> model) {
            model.setUpdatedTime(LocalDateTime.now());
            model.setCreatedTime(LocalDateTime.now());
            if (LoginThread.isLogin()) {
                model.setCreatedBy(LoginThread.getLoginId());
                model.setUpdatedBy(LoginThread.getLoginId());
            }
            return;
        }

        if (metaObject.getOriginalObject() instanceof BaseLogModel<?> model) {
            model.setCreatedTime(LocalDateTime.now());
            return;
        }

        this.strictInsertFill(metaObject, properties.getCreatedTime(), LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, properties.getUpdatedTime(), LocalDateTime.class, LocalDateTime.now());
        if (LoginThread.isLogin()) {
            this.strictUpdateFill(metaObject, properties.getUpdatedBy(), String.class, LoginThread.getLoginId());
            this.strictInsertFill(metaObject, properties.getCreatedBy(), String.class, LoginThread.getLoginId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNull(metaObject)) {
            return;
        }

        fillTenantId(metaObject);

        if (metaObject.getOriginalObject() instanceof BaseModel<?> model) {
            if (properties.isCover() || model.getUpdatedTime() == null) {
                model.setUpdatedTime(LocalDateTime.now());
            }
            if (LoginThread.isLogin() && (properties.isCover() || model.getUpdatedBy() == null)) {
                model.setUpdatedBy(LoginThread.getLoginId());
            }
            return;
        }

        this.strictUpdateFill(metaObject, properties.getUpdatedTime(), LocalDateTime.class, LocalDateTime.now());
        if (LoginThread.isLogin()) {
            this.strictUpdateFill(metaObject, properties.getUpdatedBy(), String.class, LoginThread.getLoginId());
        }
    }

    public void fillTenantId(MetaObject metaObject) {
        optional.ifPresent(handler -> {

            TableName annotation = metaObject.getOriginalObject().getClass().getAnnotation(TableName.class);
            if (annotation == null) {
                return;
            }
            if (handler.ignoreTable(annotation.value())) {
                return;
            }
            Expression expression = handler.getTenantId();
            if (expression instanceof StringValue string) {
                this.strictInsertFill(metaObject, handler.getTenantIdColumn(), String.class, string.getValue());
            }
        });
    }
}